package com.ellecity06.common.http

import com.ellecity06.common.BuildConfig
import com.ellecity06.common.http.tls.Tls12SocketFactory
import com.ellecity06.common.http.tls.TrustAllManager
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager

/**
 * Retrofit客户端的
 */
abstract class BaseRetrofitClient {

    companion object CLIENT {
        private const val TIME_OUT = 10
    }

    private val client: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder()

            .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
        handleBuilder(builder)
        //处理https协议
        var sc: SSLContext?
        val tm = TrustAllManager()
        try {
            sc = SSLContext.getInstance("TLS")
            sc.init(null, arrayOf<TrustManager>(tm), SecureRandom())
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            sc = null
        }
        if (sc != null) {
            builder.sslSocketFactory(Tls12SocketFactory(sc.socketFactory), tm)
                .hostnameVerifier { _, _ -> true }
                .build()
        } else {
            builder.hostnameVerifier { _, _ -> true }
                .build()
        }
        builder.addInterceptor(getHttpLoggingInterceptor())
        builder.build()
    }

    private fun getHttpLoggingInterceptor(): HttpLoggingInterceptor {
        val logging = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            logging.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logging.level = HttpLoggingInterceptor.Level.NONE
        }
        return logging
    }

    abstract fun handleBuilder(builder: OkHttpClient.Builder)

    open fun <Service> getService(serviceClass: Class<Service>, baseUrl: String): Service {
        return Retrofit.Builder()
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(baseUrl)
            .build()
            .create(serviceClass)
    }
}
